﻿using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Controls.Primitives;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using System.Xml.Linq;
using CommunitySystem.Assert;
using CommunitySystem.Ctrls;
using CommunitySystem.PageView.AdvancedCustomerQuery;
using CommunitySystem.Views;
using EHR.Common;
using org.in2bits.MyXls;
using org.in2bits.MyXls.ByteUtil;
using System.IO;

namespace CommunitySystem.PageView
{
    public partial class CustomerizeControl : AsyncCtrl, IReturnListenerc
    {
        private GridLength _lastColLeftLength;
        private GridLength _lastColRightLength;
        private CustomerQuery.CustomerQueryClient client = null;
        private EmpbasicService.EmpBasicServiceClient empClient = null;
        public CustomerizeControl(int pid, BusyIndicator busyIndicator)
        {
            InitializeComponent();
            OrgIDs.Clear();
            client = new CustomerQuery.CustomerQueryClient();
            empClient = new EmpbasicService.EmpBasicServiceClient();
            client.GetQuery_CustomerQueryCompleted += new EventHandler<CustomerQuery.GetQuery_CustomerQueryCompletedEventArgs>(client_GetQuery_CustomerQueryCompleted);
            client.DeleteQuery_CustomerQueryCompleted += new EventHandler<CustomerQuery.DeleteQuery_CustomerQueryCompletedEventArgs>(client_DeleteQuery_CustomerQueryCompleted);
            client.GetQuery_CustomerQueryAsync("LoginUser='" + Session.LoginUser.LoginName + "' or IsTemplete=1");
            client.QueryDataCompleted += new EventHandler<CustomerQuery.QueryDataCompletedEventArgs>(client_QueryDataCompleted);
            empClient.GetDengLuJueSeCompleted += new EventHandler<EmpbasicService.GetDengLuJueSeCompletedEventArgs>(Client_GetDengLuJueSeCompleted);
            empClient.GetDengLuJueSeAsync(Session.LoginUser.LoginName);
        }
        void Client_GetDengLuJueSeCompleted(object sender, EmpbasicService.GetDengLuJueSeCompletedEventArgs e)
        {
            if (e.Result != "人事干部")
            {

                empClient.GetOrgForHRModelCompleted -= new EventHandler<EmpbasicService.GetOrgForHRModelCompletedEventArgs>(Client_GetOrgForHRModelCompleted);
                empClient.GetOrgForHRModelCompleted += new EventHandler<EmpbasicService.GetOrgForHRModelCompletedEventArgs>(Client_GetOrgForHRModelCompleted);
                empClient.GetOrgForHRModelAsync(0);
            }
            else
            {

                empClient.GetDengLuOrgCompleted += new EventHandler<EmpbasicService.GetDengLuOrgCompletedEventArgs>(Client_GetDengLuOrgCompleted);
                empClient.GetDengLuOrgAsync(Session.LoginUser.LoginName);
                //colLeft.Width = new GridLength(0);
                //colSplit.Width = new GridLength(0);
            }
        }

        void Client_GetOrgForHRModelCompleted(object sender, EmpbasicService.GetOrgForHRModelCompletedEventArgs e)
        {
            var root = e.Result.Where(c => c.ParentID == 0).FirstOrDefault();
            CheckBox cb =new CheckBox() { Content = root.Name } ;
            var rootItem = new TreeViewItem() { Header = cb, DataContext = root};
            cb.Tag = rootItem;
            cb.Click += new RoutedEventHandler(cb_Click);
            AddNoteToTree((int)root.ID, rootItem, e.Result);
            org.Items.Add(rootItem);
        }

        

        void AddNoteToTree(int parentid, TreeViewItem pitme, ObservableCollection<CommunitySystem.EmpbasicService.OrgForHRModel> source)
        {
            foreach (var model in source.Where(c => c.ParentID == parentid))
            {
                CheckBox cb = new CheckBox() { Content = model.Name };
                var item = new TreeViewItem() { Header = cb, DataContext = model };
                cb.Tag = item;
                AddNoteToTree((int)model.ID, item, source);
                cb.Click += new RoutedEventHandler(cb_Click);
                pitme.Items.Add(item);
            }
        }

        void Client_GetDengLuOrgCompleted(object sender, EmpbasicService.GetDengLuOrgCompletedEventArgs e)
        {

            empClient.GetOrgForHRModelbyIDsCompleted -= new EventHandler<EmpbasicService.GetOrgForHRModelbyIDsCompletedEventArgs>(Client_GetOrgForHRModelbyIDsCompleted);
            empClient.GetOrgForHRModelbyIDsCompleted += new EventHandler<EmpbasicService.GetOrgForHRModelbyIDsCompletedEventArgs>(Client_GetOrgForHRModelbyIDsCompleted);
            empClient.GetOrgForHRModelbyIDsAsync("(" + e.Result + ")");
        }

        void Client_GetOrgForHRModelbyIDsCompleted(object sender, EmpbasicService.GetOrgForHRModelbyIDsCompletedEventArgs e)
        {
            foreach (var model in e.Result)
            {
                CheckBox cb = new CheckBox() { Content = model.Name };
                TreeViewItem item = new TreeViewItem() { Header = cb, DataContext = model };
                cb.Tag = item;
                cb.Click += new RoutedEventHandler(cb_Click);
                org.Items.Add(item);
            }
        }

        private List<int> OrgIDs = new List<int>();
        void cb_Click(object sender, RoutedEventArgs e)
        {
            CheckBox cb = sender as CheckBox;
            TreeViewItem tvi = cb.Tag as TreeViewItem;
            EmpbasicService.OrgForHRModel model = tvi.DataContext as EmpbasicService.OrgForHRModel;
            if (cb.IsChecked == true)
            {                
                OrgIDs.Add((int)model.ID);
            }
            else
            {
                if (OrgIDs.Contains((int)model.ID))
                    OrgIDs.Remove((int)model.ID);
            }
            if (tvi.Items.Count > 0)
            {
                foreach (TreeViewItem item in tvi.Items)
                {
                    CheckBox cbc = item.Header as CheckBox;
                    cbc.IsChecked = cb.IsChecked;
                    cb_Click(cbc, null);
                }
            }
        }

        FlipSwitchForQuery flip = null;
        void client_QueryDataCompleted(object sender, CustomerQuery.QueryDataCompletedEventArgs e)
        {
            if (e.Error != null)
            {
                SilverlightMessageBoxLibrary.Message.ErrorMessage(e.Error.Message);
                return;
            }
            CommunitySystem.CustomerQuery.Query_CustomerQuery item = e.UserState as CommunitySystem.CustomerQuery.Query_CustomerQuery;
            try
            {
                xBusy.IsBusy = false;
                uc.Content = null;
                string ids = GeneratorOrgs();
                flip = new FlipSwitchForQuery(item, ids, this);
                uc.Content = flip;
                _docx = XDocument.Parse(e.Result);                
                DrawGrid(flip.tableGrid, _docx);
                //flip.SetNewPage(control, control.Nav);
                
            }
            catch (Exception ex)
            {
                SilverlightMessageBoxLibrary.Message.ErrorMessage("查询设置出错");
            }
        }
        private int CellHeight = 30;
        private int CellWeight = 140;
        public XDocument _docx = null;
        private Grid _grid = null;
        private System.Windows.Controls.ContextMenu _ContextMenu = null;
        private void GeneratorMenu()
        {
            _ContextMenu = new System.Windows.Controls.ContextMenu();//新建右键菜单
            MenuItem mi = new MenuItem();//新建右键菜单项
            //mi.Header = "调整行高";
            //mi.Click += MenuItem_Click;//为菜单项注册事件      
            //_ContextMenu.Items.Add(mi);
            mi = new MenuItem();//新建右键菜单项
            mi.Header = "调整列宽";
            mi.Click += MenuItem_Click;//为菜单项注册事件      
            _ContextMenu.Items.Add(mi);
            //ContextMenuService.SetContextMenu(btnRight, cm);//为控件绑定右键菜单
        }


        public void DrawGrid(Grid grid ,XDocument docx)
        {
            if (docx != null)
            {
                if (grid != null)
                    _grid = grid;
                else
                    grid = _grid;
                GeneratorMenu();
                grid.RowDefinitions.Clear();
                grid.ColumnDefinitions.Clear();
                grid.Children.Clear();
             
                
                XElement root = docx.Root;
                XAttribute rownumbers = root.Attribute("rownumbers");
                XAttribute colnumbers = root.Attribute("colnumbers");
                int rn = int.Parse(rownumbers.Value);
                int cn = int.Parse(colnumbers.Value);
                for (int i = 0; i < rn; i++)
                {
                    grid.RowDefinitions.Add(new RowDefinition() { Height = new GridLength(CellHeight, GridUnitType.Star) });
                }
                for (int i = 0; i < cn; i++)
                {
                    grid.ColumnDefinitions.Add(new ColumnDefinition() { Width = new GridLength(CellWeight, GridUnitType.Star) });
                }
                Border b = new Border() { BorderThickness = new Thickness(1, 1, 1, 1), BorderBrush = new SolidColorBrush(System.Windows.Media.Colors.Black) };
                Grid.SetColumn(b, 0);
                Grid.SetRow(b, 0);
                Grid.SetColumnSpan(b, cn);
                Grid.SetRowSpan(b, rn);
                XElement rows = root.Element("rows");
                grid.Children.Add(b);
                foreach (var row in rows.Elements("row"))
                {
                    foreach (XElement cell in row.Elements("cell"))
                    {
                        string name = string.Empty;
                        string value = string.Empty;
                        int colIndex = 0;
                        int rowIndex = 0;
                        int rowspan = 1;
                        int colspan = 1;
                        string sql = string.Empty;
                        foreach (XAttribute a in cell.Attributes())
                        {
                            if (string.IsNullOrEmpty(a.Value))
                                continue;
                            switch (a.Name.LocalName)
                            {
                                case "name":
                                    name = a.Value;
                                    break;
                                case "value":
                                    value = a.Value;
                                    break;
                                case "col":
                                    colIndex = int.Parse(a.Value);
                                    break;
                                case "row":
                                    rowIndex = int.Parse(a.Value);
                                    break;
                                case "rowspan":
                                    rowspan = int.Parse(a.Value);
                                    break;
                                case "colspan":
                                    colspan = int.Parse(a.Value);
                                    break;
                                case "sql":
                                    sql = a.Value;
                                    break;
                            }
                        }
                        Border borderCell = new Border() { BorderThickness = new Thickness(1, 1, 0, 0), MinWidth=120 , MinHeight=30  ,BorderBrush = new SolidColorBrush(System.Windows.Media.Colors.Black), Background = new SolidColorBrush(System.Windows.Media.Colors.LightGray) };
                        borderCell.MouseRightButtonDown += new MouseButtonEventHandler(borderCell_MouseRightButtonDown);
                        ContextMenuService.SetContextMenu(borderCell, _ContextMenu);//右键菜单
                        Grid.SetColumn(borderCell, colIndex);
                        Grid.SetRow(borderCell, rowIndex);
                        Grid.SetColumnSpan(borderCell, colspan);
                        Grid.SetRowSpan(borderCell, rowspan);
                        if (string.IsNullOrEmpty(sql))//不需要钻取
                        {
                            TextBlock tb = new TextBlock() { Text = value, VerticalAlignment = System.Windows.VerticalAlignment.Center, HorizontalAlignment = System.Windows.HorizontalAlignment.Center, Width = CellWeight, TextWrapping= TextWrapping.Wrap, TextAlignment= TextAlignment.Center };
                            borderCell.Child = tb;
                            
                        }
                        else
                        {
                            HyperlinkButton hlb = new HyperlinkButton() { Content = value, Name = name, VerticalAlignment = System.Windows.VerticalAlignment.Center, HorizontalAlignment = System.Windows.HorizontalAlignment.Center, Tag = cell };
                            borderCell.Child = hlb;
                            hlb.Click += new RoutedEventHandler(hlb_Click);
                        }

                        if (colIndex == cn - 1)
                        {
                            var thick = borderCell.BorderThickness;
                            thick.Right = 1;
                            borderCell.BorderThickness = thick;
                        }

                        if (rowIndex == rn - 1)
                        {
                            var thick = borderCell.BorderThickness;
                            thick.Bottom = 1;
                            borderCell.BorderThickness = thick;
                        }
                        
                        grid.Children.Add(borderCell);
                    }
                }
            }
        }

        void borderCell_MouseRightButtonDown(object sender, MouseButtonEventArgs e)
        {
            _ContextMenu.IsOpen = true;
           Border ui = sender as Border;
           int colspan = Grid.GetColumnSpan(ui);
           int rowspan = Grid.GetRowSpan(ui);
           var cm =  ContextMenuService.GetContextMenu(ui);
           foreach (MenuItem item in cm.Items)
           {
               item.IsEnabled = true;
               item.Tag = ui;
               switch (item.Header.ToString())
               {
                   case "调整行高":
                       if (rowspan > 1)
                           item.IsEnabled = false;
                       break;
                   case "调整列宽":
                       if (colspan > 1)
                           item.IsEnabled = false;
                       break;
               }
           }
            cm.HorizontalOffset = e.GetSafePosition(ui).X - ui.ActualWidth;
            cm.VerticalOffset = e.GetSafePosition(sender as UIElement).Y- ui.ActualHeight;
            cm.IsOpen = true;
            e.Handled = true;

            
        }



        private void MenuItem_Click(object sender, RoutedEventArgs e)
        {
            MenuItem mi = sender as MenuItem;
            Border b = mi.Tag as Border;
            SilverlightMessageBoxLibrary.CustomMessage cm = null;
            switch (mi.Header.ToString())
            {
                case "调整行高":
                    var rowindex = Grid.GetRow(b);
                    var rowHeight = (b.Parent as Grid).RowDefinitions[rowindex].ActualHeight;
                    cm = new SilverlightMessageBoxLibrary.CustomMessage("请输入行高?", SilverlightMessageBoxLibrary.CustomMessage.MessageType.TextInput, null);
                    cm.Input = rowHeight + "";
                    cm.OKButton.Click += (sender1, e1) =>
                    {
                        try
                        {
                            int rh = int.Parse(cm.Input);
                            (b.Parent as Grid).RowDefinitions[rowindex].Height = new GridLength(rh);

                        }
                        catch (Exception ex)
                        {
                        }
                    };
                    break;
                case "调整列宽":
                    //var colindex = Grid.GetColumn(b);
                    //var colwidth = (b.Parent as Grid).RowDefinitions[colindex].ActualHeight;
                    //cm = new SilverlightMessageBoxLibrary.CustomMessage("请输入列宽?", SilverlightMessageBoxLibrary.CustomMessage.MessageType.TextInput, null);
                    //cm.Input = colwidth + "";
                    //cm.OKButton.Click += (sender1, e1) =>
                    //{
                    //    try
                    //    {
                    //        int rh = int.Parse(cm.Input);
                    //        (b.Parent as Grid).ColumnDefinitions[colindex].Width = new GridLength(rh);

                    //    }
                    //    catch (Exception ex)
                    //    {
                    //    }
                   //};
                    break;
            }
            if (cm != null)
                cm.Show();

            //MessageBox.Show(mi.Header.ToString());
        }

     

        

        void hlb_Click(object sender, RoutedEventArgs e)//钻取数据
        {
            var item = lbViews.SelectedItem as CommunitySystem.CustomerQuery.Query_CustomerQuery;
            HyperlinkButton hlb = sender as HyperlinkButton;
            if (hlb != null  )
            {
                int count = int.Parse(hlb.Content.ToString());
                if (count > 0)
                {
                    
                    XElement ele = hlb.Tag as XElement;
                    ColumnsInSelectControl view = new ColumnsInSelectControl(ele) { Nav = flip.pageFrame as NavMoveSwitch };
                    Nav.ShowNextPage(item.Name, view, flip.newPage as IReturnListenerc);
                }
                else
                    SilverlightMessageBoxLibrary.Message.InfoMessage("无数据");

            }

           
        }

        void client_DeleteQuery_CustomerQueryCompleted(object sender, CustomerQuery.DeleteQuery_CustomerQueryCompletedEventArgs e)
        {
            if (e.Result == true)
            {
                SilverlightMessageBoxLibrary.Message.InfoMessage("删除成功");
            }
            client.GetQuery_CustomerQueryAsync("LoginUser='" + Session.LoginUser.LoginName + "' or IsTemplete=1");
        }

        void client_GetQuery_CustomerQueryCompleted(object sender, CustomerQuery.GetQuery_CustomerQueryCompletedEventArgs e)
        {
            lbViews.ItemsSource = null;
            lbViews.ItemsSource = e.Result;
        }

        public void BeginReturn()
        {
            
        }

        private void GridSpliteTo_ToLeft(object sender, EventArgs e)
        {
            //已经到最左边，直接返回
            if (colLeft.Width.Value == 0)
            {
                return;
            }

            //
            if (colRight.Width.Value == 0)
            {
                colLeft.Width = _lastColLeftLength;
                colRight.Width = _lastColRightLength;
            }
            else
            {
                _lastColLeftLength = colLeft.Width;
                _lastColRightLength = colRight.Width;

                colLeft.Width = new GridLength(0);
                colRight.Width = new GridLength(150, GridUnitType.Star);
            }
        }

        private void GridSpliteTo_ToRight(object sender, EventArgs e)
        {
            if (colRight.Width.Value == 0)
            {
                return;
            }

            if (colLeft.Width.Value == 0)
            {
                colLeft.Width = _lastColLeftLength;
                colRight.Width = _lastColRightLength;
            }
            else
            {
                _lastColLeftLength = colLeft.Width;
                _lastColRightLength = colRight.Width;

                colRight.Width = new GridLength(0);
                colLeft.Width = new GridLength(300, GridUnitType.Star);
            }
        }

        private void lbViews_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            //var item = lbViews.SelectedItem as CommunitySystem.CustomerQuery.Query_CustomerQuery;
            //if (lbViews.SelectedItem != null && item != null)
            //{

            //    client.QueryDataAsync(item.ID);   
            //}
        }

        private void btnAdd_Click(object sender, RoutedEventArgs e)
        {
            CustomerizeQueryWindow window = new CustomerizeQueryWindow(0);
            window.Closed -= new EventHandler(window_Closed);
            window.Closed += new EventHandler(window_Closed);
            window.Show();
            //CustomerDesignView view = new CustomerDesignView() { Nav = Nav };
            //_customerDesignView = view;
            //this.IsEnabled = false;
            //Nav.ShowNextPage("新建视图", view, this);
        }

        void window_Closed(object sender, EventArgs e)
        {
            ChildWindow cw = sender as ChildWindow;
            if (cw.DialogResult == true)
            {
                client.GetQuery_CustomerQueryAsync("LoginUser='" + Session.LoginUser.LoginName + "' or IsTemplete=1");
            }
        }

        private void btnEdit_Click(object sender, RoutedEventArgs e)
        {
            if (lbViews.SelectedItem == null)
            {
                return;
            }
            var entity = lbViews.SelectedItem as CommunitySystem.CustomerQuery.Query_CustomerQuery;

            CustomerizeQueryWindow window = new CustomerizeQueryWindow(entity.ID);
            window.Closed -= new EventHandler(window_Closed);
            window.Closed += new EventHandler(window_Closed);
            window.Show();
        }

        private void btnDelete_Click(object sender, RoutedEventArgs e)
        {
            if (lbViews.SelectedItem == null)
            {
                return;
            }

           

            if (MessageBox.Show("确实要删除吗？", "提示", MessageBoxButton.OKCancel) != MessageBoxResult.OK)
            {
                return;
            }
            var entity = lbViews.SelectedItem as CommunitySystem.CustomerQuery.Query_CustomerQuery;
            if (entity.IsTemplete == true && entity.LoginUser != Session.LoginUser.LoginName)
            {
                SilverlightMessageBoxLibrary.Message.ErrorMessage("您不是该模版的创建者,您没有该模版的删除权限");
                return;
            }
            client.DeleteQuery_CustomerQueryAsync(entity.ID);
           
        }

        private void ImageButton_Click(object sender, RoutedEventArgs e)
        {
            var item = lbViews.SelectedItem as CommunitySystem.CustomerQuery.Query_CustomerQuery;
            string ids = GeneratorOrgs();
            if (string.IsNullOrEmpty(ids))
            {
                SilverlightMessageBoxLibrary.Message.ErrorMessage("请选择要查询的单位?");
                return;
            }
            if (lbViews.SelectedItem != null && item != null)
            {
                GridSpliteTo_ToLeft(null, null);
                if(flip != null && flip.tableGrid != null)
                    flip.tableGrid.Children.Clear();
                xBusy.IsBusy = true;
                client.QueryDataAsync(item.ID, ids, DateTime.Now.Year, item);
            }
        }

        private string GeneratorOrgs()
        {
            string ids = string.Empty;
            if (OrgIDs.Count>0)
            {
                foreach (int id in OrgIDs)
                {
                    ids += string.IsNullOrEmpty(ids) ? id + "" : ", " + id + ""; 
                }
            }
            return ids;
        }

        /// <summary>
        /// 根据xml导出Excel
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void HyperlinkButton_Click(object sender, RoutedEventArgs e)
        {
            if (_docx != null)
            {
                var saveFile = new SaveFileDialog() { Filter = "Excel 1997-2003| *.xls" };
                if (saveFile.ShowDialog() == false)
                    return;
                org.in2bits.MyXls.XlsDocument xls = new org.in2bits.MyXls.XlsDocument();
                xls.FileName = string.Format("{0}.xls", this.title.Text);
                var sheet = xls.Workbook.Worksheets.Add("Sheet 1");
             
                XElement root = _docx.Root;
                XElement rows = root.Element("rows");
                List<org.in2bits.MyXls.MergeArea> list = new List<org.in2bits.MyXls.MergeArea>();
                org.in2bits.MyXls.XF xf = xls.NewXF();
                xf.HorizontalAlignment = HorizontalAlignments.Centered;
                xf.VerticalAlignment = VerticalAlignments.Centered;

                xf.UseBorder = true; // 使用边框
                xf.LeftLineStyle = 1;
                xf.TopLineStyle = 1;
                xf.RightLineStyle = 1;
                xf.BottomLineStyle = 1;

              
                int colCount = 0;
              
                foreach (XElement row in rows.Elements("row"))
                {
                   
                        ushort rowindex = (ushort)(ushort.Parse(row.Attribute("rowindex").Value) + 2);
                        sheet.Rows.AddRow(rowindex);
                       
                        foreach (XElement cell in row.Elements("cell"))
                        {
                            ushort _row = (ushort)(ushort.Parse(cell.Attribute("row").Value) + 2);
                            ushort _col = (ushort)(ushort.Parse(cell.Attribute("col").Value) + 1);
                            ushort rowspan = ushort.Parse(cell.Attribute("rowspan").Value);
                            ushort colspan = ushort.Parse(cell.Attribute("colspan").Value);
                            string value = cell.Attribute("value").Value;
                            sheet.Cells.Add(_row, _col, value, xf);
                            colCount = _col;
                            if (rowspan > 1 || colspan > 1)
                            {
                                list.Add(new org.in2bits.MyXls.MergeArea(_row, _row + rowspan - 1, _col, _col + colspan - 1));
                            }

                            ColumnInfo col0 = new ColumnInfo(xls, sheet); // 列对象
                            col0.ColumnIndexStart = (ushort)(ushort.Parse(cell.Attribute("col").Value)); // 起始列为第1列，索引从0开始
                            col0.ColumnIndexEnd = (ushort)(ushort.Parse(cell.Attribute("col").Value)); ; // 终止列为第1列，索引从0开始
                            col0.Width = (ushort)((cell.Attribute("col").Value.Length+10)*256); // 列的宽度计量单位为 1/256 字符宽
                            sheet.AddColumnInfo(col0); // 把格式附加到sheet页上
                        }
                    
                }
                //标题
                sheet.Cells.Add(1, 1, this.title.Text, xf);
                list.Add(new org.in2bits.MyXls.MergeArea(1,1,1,colCount));


                foreach (var l in list)
                {
                    sheet.AddMergeArea(l);
                }
                try
                {
                    System.IO.Stream stream = saveFile.OpenFile();
                    xls.Save(stream);
                    stream.Dispose();
                    SilverlightMessageBoxLibrary.Message.InfoMessage("导出成功!");
                }
                catch (Exception ex)
                {
                    SilverlightMessageBoxLibrary.Message.ErrorMessage("导出失败:\n" + ex.Message);
                }
            }
        }

        /// <summary>
        /// 行列互换
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void ImageButton_Click2(object sender, System.Windows.RoutedEventArgs e)
        {
        	// 在此处添加事件处理程序实现。
            if (_docx != null)
            {
                var doc = new XDocument(new XDeclaration("1.0", "utf-8", "yes"));
                var _root = _docx.Root;
                string rownumbers = _root.Attribute("colnumbers").Value;
                string colnumbers = _root.Attribute("rownumbers").Value;
                string maxrowlevel = _root.Attribute("maxcollevel").Value;
                string maxcollevel = _root.Attribute("maxrowlevel").Value;
                XElement root = new XElement("root", new XAttribute("rownumbers", rownumbers)
                                                    , new XAttribute("colnumbers", colnumbers)
                                                    , new XAttribute("maxrowlevel", maxrowlevel)
                                                    , new XAttribute("maxcollevel", maxcollevel));
                var rows =  new XElement("rows");
                Dictionary<int, XElement> rowindex_row = new Dictionary<int, XElement>();
                foreach (XElement _row in _root.Element("rows").Elements("row"))
                {
                    foreach (XElement _cell in _row.Elements("cell"))
                    {
                        XElement cell = new XElement("cell");
                        string name = _cell.Attribute("name").Value;
                        string value = _cell.Attribute("value").Value;
                        string sql = _cell.Attribute("sql").Value;
                        int row = int.Parse(_cell.Attribute("col").Value);
                        string col = _cell.Attribute("row").Value;
                        string colspan = _cell.Attribute("rowspan").Value;
                        string rowspan = _cell.Attribute("colspan").Value;
                        var ps = _cell.Elements("sqlparameter");
                        cell.Add(new XAttribute("name", name));
                        cell.Add(new XAttribute("value", value));
                        cell.Add(new XAttribute("sql", sql));
                        cell.Add(new XAttribute("row", row));
                        cell.Add(new XAttribute("col", col));
                        cell.Add(new XAttribute("colspan", colspan));
                        cell.Add(new XAttribute("rowspan", rowspan));
                        if (ps != null)
                        {
                            cell.Add(ps);
                        }
                        if (!rowindex_row.Keys.Contains(row))
                        {
                            rowindex_row.Add(row, new XElement("row", new XAttribute("rowindex", row)));
                            rows.Add(rowindex_row[row]);
                        }
                        
                        rowindex_row[row].Add(cell);                        
                            
                    }
                }
                
                root.Add(rows);
                doc.Add(root);
                _docx = doc;
                DrawGrid(null, _docx);

            }
        }

        private void btnOut_Click(object sender, RoutedEventArgs e)
        {

        }
        private Stream _stream;
        public void ExportExcel()
        {
            SaveFileDialog dlg = new SaveFileDialog()
            {
                Filter = "Excel文件 (*.xls)|*.xls"
            };

            if (!(bool)dlg.ShowDialog())
            {
                return;
            }
            try
            {
                _stream = dlg.OpenFile();
            }
            catch
            {
                MessageBox.Show("其它程序正在使用该文件，请关闭使用该文件的程序后重试！");
                return;
            }
        }
    }



}
